<template>
  <div class="example-container">
    <h2>👀 watch() - 数据监听器</h2>
    
    <div class="demo-section">
      <h3>魔法温度监控器</h3>
      <div class="temperature-monitor">
        <div class="gauge">
          <div class="temperature-value" :style="{ transform: `translateY(calc(${100 - temp * 5}% - 10px))` }">
            {{ temp }}°C
          </div>
          <div class="gauge-scale">
            <div class="scale-mark" v-for="i in 20" :key="i" :style="{ top: `${100 - i * 5}%` }"></div>
            <div class="scale-label" style="top: 0%">20°C</div>
            <div class="scale-label" style="top: 50%">10°C</div>
            <div class="scale-label" style="top: 100%">0°C</div>
          </div>
        </div>
        
        <div class="temperature-controls">
          <button @click="increaseTemperature" class="control-btn hot">➕ 升温</button>
          <button @click="decreaseTemperature" class="control-btn cold">➖ 降温</button>
          <button @click="resetTemperature" class="control-btn reset">🔄 重置</button>
        </div>
        
        <div class="status-display" :class="temperatureStatus">
          {{ statusMessage }}
        </div>
        
        <div class="history">
          <h4>温度变化历史:</h4>
          <div class="history-items">
            <div v-for="(record, index) in temperatureHistory" :key="index" class="history-item">
              {{ record }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="demo-section">
      <h3>表单验证示例</h3>
      <div class="form-validation">
        <form @submit.prevent="submitForm" class="validation-form">
          <div class="form-group">
            <label for="username">用户名:</label>
            <input 
              id="username" 
              v-model="formData.username" 
              type="text" 
              placeholder="请输入用户名"
              :class="{ 'error': errors.username }"
            />
            <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
          </div>
          
          <div class="form-group">
            <label for="email">邮箱:</label>
            <input 
              id="email" 
              v-model="formData.email" 
              type="email" 
              placeholder="请输入邮箱"
              :class="{ 'error': errors.email }"
            />
            <div v-if="errors.email" class="error-message">{{ errors.email }}</div>
          </div>
          
          <div class="form-group">
            <label for="password">密码:</label>
            <input 
              id="password" 
              v-model="formData.password" 
              type="password" 
              placeholder="请输入密码"
              :class="{ 'error': errors.password }"
            />
            <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
          </div>
          
          <button type="submit" class="submit-btn" :disabled="!isFormValid">提交表单</button>
        </form>
        
        <div v-if="formSubmitted" class="success-message">
          ✅ 表单提交成功！
        </div>
      </div>
    </div>
    
    <div class="code-section">
      <h3>📝 代码说明</h3>
      <p><strong>watch()</strong> 用于监听响应式数据的变化，并在变化时执行自定义逻辑。</p>
      <p>可以监听单个响应式数据，也可以监听多个数据；可以立即执行，也可以深度监听。</p>
      <p>适用于需要在数据变化时执行副作用的场景，如日志记录、异步请求、表单验证等。</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';

// 使用let而不是ref来避免TypeScript类型问题
let temp: number = 10;
const temperatureHistory = ref<string[]>([]);

// 计算属性 - 温度状态
const temperatureStatus = computed(() => {
  if (temp >= 15) return 'hot';
  if (temp <= 5) return 'cold';
  return 'normal';
});

const statusMessage = computed(() => {
  if (temp >= 15) return '🔥 温度过高！需要降温！';
  if (temp <= 5) return '❄️ 温度过低！需要升温！';
  return '😊 温度适宜！';
});

// 监听温度变化
const updateTemp = (newTemp: number) => {
  const oldValue = temp;
  temp = newTemp;
  
  // 记录历史
  const timestamp = new Date().toLocaleTimeString();
  temperatureHistory.value.unshift(`[${timestamp}] 温度从 ${oldValue}°C 变为 ${newTemp}°C`);
  
  // 限制历史记录数量
  if (temperatureHistory.value.length > 5) {
    temperatureHistory.value.pop();
  }
  
  console.log(`温度变化: ${oldValue}°C -> ${newTemp}°C`);
};

// 方法
const increaseTemperature = () => {
  if (temp < 20) {
    updateTemp(temp + 1);
  }
};

const decreaseTemperature = () => {
  if (temp > 0) {
    updateTemp(temp - 1);
  }
};

const resetTemperature = () => {
  updateTemp(10);
};

// 表单验证示例
interface FormData {
  username: string;
  email: string;
  password: string;
}

interface FormErrors {
  username: string;
  email: string;
  password: string;
}

const formData = reactive<FormData>({
  username: '',
  email: '',
  password: ''
});

const errors = reactive<FormErrors>({
  username: '',
  email: '',
  password: ''
});

const formSubmitted = ref(false);

// 验证函数
const validateUsername = () => {
  if (!formData.username.trim()) {
    errors.username = '用户名不能为空';
    return false;
  }
  if (formData.username.length < 3) {
    errors.username = '用户名至少需要3个字符';
    return false;
  }
  errors.username = '';
  return true;
};

const validateEmail = () => {
  if (!formData.email.trim()) {
    errors.email = '邮箱不能为空';
    return false;
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(formData.email)) {
    errors.email = '请输入有效的邮箱地址';
    return false;
  }
  errors.email = '';
  return true;
};

const validatePassword = () => {
  if (!formData.password) {
    errors.password = '密码不能为空';
    return false;
  }
  if (formData.password.length < 6) {
    errors.password = '密码至少需要6个字符';
    return false;
  }
  errors.password = '';
  return true;
};

// 表单有效性计算属性
const isFormValid = computed(() => {
  return validateUsername() && validateEmail() && validatePassword();
});

// 提交表单
const submitForm = () => {
  if (!isFormValid.value) {
    // 触发表单验证
    validateUsername();
    validateEmail();
    validatePassword();
    return;
  }
  
  // 模拟提交
  formSubmitted.value = true;
  console.log('表单数据:', formData);
  
  // 重置表单（实际应用中可能不需要）
  setTimeout(() => {
    formSubmitted.value = false;
  }, 3000);
};
</script>

<style scoped>
.example-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

h2 {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 30px;
  font-size: 28px;
}

.demo-section {
  background: white;
  padding: 25px;
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

h3 {
  color: #3498db;
  margin-bottom: 20px;
  font-size: 20px;
}

/* 温度监控器样式 */
.temperature-monitor {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.gauge {
  position: relative;
  width: 80px;
  height: 200px;
  background: linear-gradient(to bottom, #ff6b6b, #4ecdc4, #3498db);
  border-radius: 40px 40px 0 0;
  overflow: hidden;
}

.temperature-value {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  background: #fff;
  color: #333;
  padding: 5px 10px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  font-weight: bold;
  transition: transform 0.3s ease;
}

.gauge-scale {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.scale-mark {
  position: absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: rgba(255, 255, 255, 0.5);
}

.scale-label {
  position: absolute;
  left: 100%;
  margin-left: 10px;
  color: #555;
  font-size: 12px;
  transform: translateY(-50%);
}

.temperature-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
}

.control-btn.hot {
  background: #e74c3c;
  color: white;
}

.control-btn.hot:hover {
  background: #c0392b;
}

.control-btn.cold {
  background: #3498db;
  color: white;
}

.control-btn.cold:hover {
  background: #2980b9;
}

.control-btn.reset {
  background: #95a5a6;
  color: white;
}

.control-btn.reset:hover {
  background: #7f8c8d;
}

.status-display {
  padding: 15px 25px;
  border-radius: 5px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.status-display.hot {
  background: #ffeaa7;
  color: #d68910;
}

.status-display.cold {
  background: #d6eaf8;
  color: #2874a6;
}

.status-display.normal {
  background: #d5f5e3;
  color: #27ae60;
}

.history {
  width: 100%;
  max-width: 400px;
}

.history h4 {
  color: #7f8c8d;
  margin-bottom: 10px;
}

.history-items {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 5px;
  max-height: 150px;
  overflow-y: auto;
}

.history-item {
  padding: 5px 0;
  font-size: 14px;
  color: #555;
  border-bottom: 1px solid #eee;
}

.history-item:last-child {
  border-bottom: none;
}

/* 表单验证样式 */
.form-validation {
  max-width: 500px;
  margin: 0 auto;
}

.validation-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: bold;
  color: #555;
}

.form-group input {
  padding: 10px;
  border: 2px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #3498db;
}

.form-group input.error {
  border-color: #e74c3c;
}

.error-message {
  color: #e74c3c;
  font-size: 14px;
}

.submit-btn {
  padding: 12px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #2980b9;
}

.submit-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.success-message {
  text-align: center;
  padding: 15px;
  background: #d5f5e3;
  color: #27ae60;
  border-radius: 5px;
  font-weight: bold;
  margin-top: 20px;
}

/* 代码说明部分 */
.code-section {
  background: #ecf0f1;
  padding: 20px;
  border-radius: 8px;
}

.code-section p {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #2c3e50;
}

.code-section strong {
  color: #e74c3c;
}
</style>